## Data overview
library(MASS)
data("Boston")
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08204   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00
#variables distribution
p <- pairs(Boston)
p
## NULL
#calculate the correlation matrix and round it
cor_matrix<-cor(Boston) 
#print the correlation matrix
cor_matrix
##                crim          zn       indus         chas         nox
## crim     1.00000000 -0.20046922  0.40658341 -0.055891582  0.42097171
## zn      -0.20046922  1.00000000 -0.53382819 -0.042696719 -0.51660371
## indus    0.40658341 -0.53382819  1.00000000  0.062938027  0.76365145
## chas    -0.05589158 -0.04269672  0.06293803  1.000000000  0.09120281
## nox      0.42097171 -0.51660371  0.76365145  0.091202807  1.00000000
## rm      -0.21924670  0.31199059 -0.39167585  0.091251225 -0.30218819
## age      0.35273425 -0.56953734  0.64477851  0.086517774  0.73147010
## dis     -0.37967009  0.66440822 -0.70802699 -0.099175780 -0.76923011
## rad      0.62550515 -0.31194783  0.59512927 -0.007368241  0.61144056
## tax      0.58276431 -0.31456332  0.72076018 -0.035586518  0.66802320
## ptratio  0.28994558 -0.39167855  0.38324756 -0.121515174  0.18893268
## black   -0.38506394  0.17552032 -0.35697654  0.048788485 -0.38005064
## lstat    0.45562148 -0.41299457  0.60379972 -0.053929298  0.59087892
## medv    -0.38830461  0.36044534 -0.48372516  0.175260177 -0.42732077
##                  rm         age         dis          rad         tax
## crim    -0.21924670  0.35273425 -0.37967009  0.625505145  0.58276431
## zn       0.31199059 -0.56953734  0.66440822 -0.311947826 -0.31456332
## indus   -0.39167585  0.64477851 -0.70802699  0.595129275  0.72076018
## chas     0.09125123  0.08651777 -0.09917578 -0.007368241 -0.03558652
## nox     -0.30218819  0.73147010 -0.76923011  0.611440563  0.66802320
## rm       1.00000000 -0.24026493  0.20524621 -0.209846668 -0.29204783
## age     -0.24026493  1.00000000 -0.74788054  0.456022452  0.50645559
## dis      0.20524621 -0.74788054  1.00000000 -0.494587930 -0.53443158
## rad     -0.20984667  0.45602245 -0.49458793  1.000000000  0.91022819
## tax     -0.29204783  0.50645559 -0.53443158  0.910228189  1.00000000
## ptratio -0.35550149  0.26151501 -0.23247054  0.464741179  0.46085304
## black    0.12806864 -0.27353398  0.29151167 -0.444412816 -0.44180801
## lstat   -0.61380827  0.60233853 -0.49699583  0.488676335  0.54399341
## medv     0.69535995 -0.37695457  0.24992873 -0.381626231 -0.46853593
##            ptratio       black      lstat       medv
## crim     0.2899456 -0.38506394  0.4556215 -0.3883046
## zn      -0.3916785  0.17552032 -0.4129946  0.3604453
## indus    0.3832476 -0.35697654  0.6037997 -0.4837252
## chas    -0.1215152  0.04878848 -0.0539293  0.1752602
## nox      0.1889327 -0.38005064  0.5908789 -0.4273208
## rm      -0.3555015  0.12806864 -0.6138083  0.6953599
## age      0.2615150 -0.27353398  0.6023385 -0.3769546
## dis     -0.2324705  0.29151167 -0.4969958  0.2499287
## rad      0.4647412 -0.44441282  0.4886763 -0.3816262
## tax      0.4608530 -0.44180801  0.5439934 -0.4685359
## ptratio  1.0000000 -0.17738330  0.3740443 -0.5077867
## black   -0.1773833  1.00000000 -0.3660869  0.3334608
## lstat    0.3740443 -0.36608690  1.0000000 -0.7376627
## medv    -0.5077867  0.33346082 -0.7376627  1.0000000
#visualize the correlation matrix
library(corrplot)
## corrplot 0.84 loaded
library(tidyverse)
## ── Attaching packages ───────────────────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 3.2.1     ✔ purrr   0.3.3
## ✔ tibble  2.1.3     ✔ dplyr   0.8.3
## ✔ tidyr   1.0.0     ✔ stringr 1.4.0
## ✔ readr   1.3.1     ✔ forcats 0.4.0
## ── Conflicts ──────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ✖ dplyr::select() masks MASS::select()

corrplot(cor_matrix, method="circle")

corrplot(cor_matrix, method="circle", type = "upper",cl.pos = "b", tl.pos = "d",tl.cex = 0.6)%>%round()

##         crim zn indus chas nox rm age dis rad tax ptratio black lstat medv
## crim       1  0     0    0   0  0   0   0   1   1       0     0     0    0
## zn         0  1    -1    0  -1  0  -1   1   0   0       0     0     0    0
## indus      0 -1     1    0   1  0   1  -1   1   1       0     0     1    0
## chas       0  0     0    1   0  0   0   0   0   0       0     0     0    0
## nox        0 -1     1    0   1  0   1  -1   1   1       0     0     1    0
## rm         0  0     0    0   0  1   0   0   0   0       0     0    -1    1
## age        0 -1     1    0   1  0   1  -1   0   1       0     0     1    0
## dis        0  1    -1    0  -1  0  -1   1   0  -1       0     0     0    0
## rad        1  0     1    0   1  0   0   0   1   1       0     0     0    0
## tax        1  0     1    0   1  0   1  -1   1   1       0     0     1    0
## ptratio    0  0     0    0   0  0   0   0   0   0       1     0     0   -1
## black      0  0     0    0   0  0   0   0   0   0       0     1     0    0
## lstat      0  0     1    0   1 -1   1   0   0   1       0     0     1   -1
## medv       0  0     0    0   0  1   0   0   0   0      -1     0    -1    1

This data has 506 obs. of 14 variables which contain information about different indicators of Boston city as per capita crime rate, index of accessibility to radial highways and etc. In the fist plot we seen the distibution of variables. It looks like only rm has a normal distribution while crime, chas, lstat are shifted to the left, age to the right and etc. In the second plot positive correlations are displayed in blue and negative correlations in red color. Color intensity and the size of the circle are proportional to the correlation coefficients. For example, the is strong positive correlation between such variables as crime and rad and tax, between indus and nox, age and tax. Negative correlations between dis and nox,age and dis, medv and lstat.

## Scaling and factor variable

#center and standardize variables
boston_scaled <- scale (Boston)
#summaries of the scaled variables
summary(boston_scaled) 
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
#class of the boston_scaled object
class(boston_scaled)
## [1] "matrix"
#change the object to data frame
boston_scaled <- as.data.frame(boston_scaled)

#create a quantile vector of crim and print it
bins <- quantile(boston_scaled$crim)
bins
##           0%          25%          50%          75%         100% 
## -0.419366929 -0.410563278 -0.390280295  0.007389247  9.924109610
#create a categorical variable 'crime'
vector <- c("low","med_low","med_high","high")
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, label=vector)

#look at the table of the new factor crime
table(crime)
## crime
##      low  med_low med_high     high 
##      127      126      126      127
# remove original crim from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)

#add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)

## Train and test sets
#number of rows in the Boston dataset 
n <- nrow(boston_scaled)
#choose randomly 80% of the rows
ind <- sample(n,  size = n * 0.8)
#create train set
train <- boston_scaled[ind,]
#create test set 
test <- boston_scaled[-ind,]
#save the correct classes from test data
correct_classes <- c(test$crime)
#remove the crime variable from test data
test <- dplyr::select(test, -crime)

str(train)
## 'data.frame':    404 obs. of  14 variables:
##  $ zn     : num  -0.487 -0.487 3.586 -0.487 1.871 ...
##  $ indus  : num  0.247 1.015 -1.409 1.015 -1.295 ...
##  $ chas   : num  -0.272 -0.272 -0.272 -0.272 -0.272 ...
##  $ nox    : num  -1.02 1.6 -1.31 1 -1.43 ...
##  $ rm     : num  -0.0749 -0.0479 0.9826 0.1357 0.2396 ...
##  $ age    : num  -0.528 0.996 -1.893 0.981 -1.303 ...
##  $ dis    : num  0.579 -0.758 1.832 -1.144 1.668 ...
##  $ rad    : num  -0.522 1.66 -0.752 1.66 -0.982 ...
##  $ tax    : num  -0.0607 1.5294 -0.037 1.5294 -0.6422 ...
##  $ ptratio: num  0.113 0.806 -0.672 0.806 -1.458 ...
##  $ black  : num  0.326 0.349 0.441 0.441 0.417 ...
##  $ lstat  : num  -0.0438 0.5303 -1.1333 1.5456 -0.6194 ...
##  $ medv   : num  -0.1449 -1.08 1.3447 -1.0256 -0.0579 ...
##  $ crime  : Factor w/ 4 levels "low","med_low",..: 1 4 1 4 1 3 4 4 3 3 ...
str(test)
## 'data.frame':    102 obs. of  13 variables:
##  $ zn     : num  -0.487 -0.487 -0.487 -0.487 -0.487 ...
##  $ indus  : num  -1.306 -1.306 -0.437 -0.437 -0.616 ...
##  $ chas   : num  -0.272 -0.272 -0.272 -0.272 -0.272 ...
##  $ nox    : num  -0.834 -0.834 -0.144 -0.144 -0.921 ...
##  $ rm     : num  1.015 1.227 -0.419 -1.017 0.691 ...
##  $ age    : num  -0.809 -0.511 0.466 1.049 -2.333 ...
##  $ dis    : num  1.07667 1.07667 0.21981 0.00136 0.91459 ...
##  $ rad    : num  -0.752 -0.752 -0.637 -0.637 -0.752 ...
##  $ tax    : num  -1.105 -1.105 -0.601 -0.601 -1.04 ...
##  $ ptratio: num  0.113 0.113 1.175 1.175 -0.257 ...
##  $ black  : num  0.416 0.441 0.329 0.218 0.315 ...
##  $ lstat  : num  -1.36 -1.025 0.282 1.172 -1.094 ...
##  $ medv   : num  1.182 1.486 -0.547 -0.971 0.442 ...

Here we scale the data which is an operation when we subtract the column means from the corresponding columns and divide the difference with standard deviation. It helps us to have normal distribution of variables later used in clastering. When we create a factor variable’crim’ and use the quantiles as the break points to the variable.Later we divide the dataset to train and test sets, so that 80% of the data belongs to the train set.

# Linear discriminant analysis
lda.fit <- lda(crime ~ ., data = train)
#print the lda.fit object
lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2450495 0.2400990 0.2450495 0.2698020 
## 
## Group means:
##                   zn      indus         chas        nox         rm
## low       0.92965428 -0.8860031 -0.073485621 -0.8632502  0.3981103
## med_low  -0.05073326 -0.2900538 -0.028797094 -0.5554578 -0.1050056
## med_high -0.36423911  0.1538763  0.006051757  0.3473873  0.1083567
## high     -0.48724019  1.0169738 -0.091728139  1.0257763 -0.4028731
##                 age        dis        rad        tax    ptratio      black
## low      -0.9251734  0.8105635 -0.7011348 -0.7095807 -0.4805581  0.3773743
## med_low  -0.2896477  0.3786594 -0.5366922 -0.4763859 -0.1161276  0.3207166
## med_high  0.4332611 -0.3513310 -0.4122780 -0.3168968 -0.2547377  0.0885178
## high      0.8186932 -0.8554448  1.6395837  1.5150965  0.7824713 -0.8219992
##                lstat        medv
## low      -0.75482265  0.50449804
## med_low  -0.13570008  0.01571291
## med_high  0.03750785  0.16150470
## high      0.86294588 -0.64976166
## 
## Coefficients of linear discriminants:
##                 LD1          LD2         LD3
## zn       0.17552615  0.736856101 -0.93859336
## indus    0.01360929 -0.236553000  0.41397977
## chas    -0.09207470  0.016722921  0.11072557
## nox      0.42119948 -0.738935230 -1.41811868
## rm      -0.10859716 -0.114204150 -0.14370344
## age      0.26927123 -0.480114007  0.14693752
## dis     -0.08840325 -0.465608530  0.46337678
## rad      3.18963696  0.981178162  0.07231998
## tax      0.01462010 -0.073725984  0.45241823
## ptratio  0.15596067 -0.008788541 -0.33270335
## black   -0.12051102  0.011834236  0.13028638
## lstat    0.26669694 -0.295075244  0.31088709
## medv     0.23917557 -0.461019360 -0.16699992
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9561 0.0341 0.0098
#the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

#target classes as numeric
classes <- as.numeric(train$crime)

#plot the lda results
plot(lda.fit, dimen = 2,col = classes,pch = classes)
lda.arrows(lda.fit, myscale = 2)

We have 4 clasters, so train data was devided in 25% 4 times with crime as target variable. In the plot we see that three clasters are overlapping while the 4rd one in quite far for them. We aslo see that such variables as zn, nox, rad, ptratio have a big impact on the model

# Predictors
#create train set
train <- boston_scaled[ind,]
#create test set 
test <- boston_scaled[-ind,]
#save the correct classes from test data
correct_classes <- c(test$crime)
#remove the crime variable from test data
test <- dplyr::select(test, -crime)
#predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)

# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
##        predicted
## correct low med_low med_high high
##       1  19       8        1    0
##       2  10      13        6    0
##       3   1       8       17    1
##       4   0       0        0   18

In the table we see that in 1 cluster of test data there are 14 low crime, 15 medium low and 1 medium high (30). In the 2 is one low, 17 medium low and 8 medium high (26). In the 3 - 6 medium low and 18 medium high (24). And in 4 22 only high. So clasters are formed from low to high.

## distances
library(MASS)
data('Boston')
#scale the data
boston_scaled <- scale (Boston)

#euclidean distance matrix
dist_eu <- (boston_scaled)
#look at the summary of the distances
summary(dist_eu)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
#manhattan distance matrix
dist_man <- dist(boston_scaled, method = "manhattan")
#look at the summary of the distances
summary(dist_man)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.2662  8.4832 12.6090 13.5488 17.7568 48.8618
# k-means clustering
km <-kmeans(boston_scaled, centers = 3)
km$cluster
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18 
##   2   1   2   2   2   2   1   1   1   1   1   1   1   1   1   1   1   1 
##  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
##  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54 
##   1   1   1   2   2   2   2   2   1   1   1   1   1   1   2   2   2   2 
##  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72 
##   2   2   2   2   2   2   1   1   2   2   2   2   2   2   1   2   2   1 
##  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90 
##   2   2   1   1   1   1   1   1   2   2   2   2   1   1   1   1   1   1 
##  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 
##   1   1   1   2   1   1   1   2   2   2   1   1   1   1   1   1   1   1 
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 
##   1   1   1   1   1   1   1   1   3   1   1   1   3   1   3   3   3   3 
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 
##   3   3   3   3   3   3   1   1   1   3   1   3   3   1   1   1   1   1 
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   2   1   1   1   2 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 
##   2   1   1   1   1   1   2   2   2   2   2   2   2   2   2   2   2   2 
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 
##   2   2   2   2   2   2   2   1   1   1   1   1   1   1   1   1   1   1 
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 
##   1   1   1   1   1   1   1   1   2   2   2   1   2   2   1   1   2   2 
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 
##   1   1   1   1   2   2   2   2   2   2   1   1   2   1   2   2   2   2 
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 
##   2   2   2   2   2   2   1   1   1   2   2   1   1   1   1   2   2   1 
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 
##   1   2   1   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 
##   2   2   2   2   2   2   1   2   1   1   2   2   2   2   2   2   2   2 
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 
##   2   2   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 
##   1   2   1   1   1   2   2   2   2   1   1   1   1   1   1   1   1   2 
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   1   2   2   1   1   2   2   2   2   2   2   2   2   2   3   3   3   3 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 
##   3   3   3   3   3   3   3   1   1   1   1   1   1   1   1   1   1   1 
## 505 506 
##   1   1
# plot the Boston dataset with clusters
pairs(boston_scaled, col=5)

#determine K
set.seed(123)
library(ggplot2)
#determine the number of clusters
k_max <- 10

#calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(boston_scaled, k)$tot.withinss})

#visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line')

#k-means clustering
km <-kmeans(boston_scaled, centers = 2)

#plot the Boston dataset with clusters
pairs(boston_scaled, col = km$cluster)

Based on the calculated distance meajure the k-classtering was maded. On the graph we see a significant change in point 2 - so the optimal number of clastters is 2.

# bonun exercise
model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)

library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', col=correct_classes)
## Warning: 'scatter3d' objects don't have these attributes: 'col'
## Valid attributes include:
## 'type', 'visible', 'showlegend', 'legendgroup', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'x', 'y', 'z', 'text', 'hovertext', 'hovertemplate', 'mode', 'surfaceaxis', 'surfacecolor', 'projection', 'connectgaps', 'line', 'marker', 'textposition', 'textfont', 'hoverinfo', 'error_x', 'error_y', 'error_z', 'xcalendar', 'ycalendar', 'zcalendar', 'scene', 'idssrc', 'customdatasrc', 'metasrc', 'xsrc', 'ysrc', 'zsrc', 'textsrc', 'hovertextsrc', 'hovertemplatesrc', 'textpositionsrc', 'hoverinfosrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', col=km$cluster)
## Warning: 'scatter3d' objects don't have these attributes: 'col'
## Valid attributes include:
## 'type', 'visible', 'showlegend', 'legendgroup', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'x', 'y', 'z', 'text', 'hovertext', 'hovertemplate', 'mode', 'surfaceaxis', 'surfacecolor', 'projection', 'connectgaps', 'line', 'marker', 'textposition', 'textfont', 'hoverinfo', 'error_x', 'error_y', 'error_z', 'xcalendar', 'ycalendar', 'zcalendar', 'scene', 'idssrc', 'customdatasrc', 'metasrc', 'xsrc', 'ysrc', 'zsrc', 'textsrc', 'hovertextsrc', 'hovertemplatesrc', 'textpositionsrc', 'hoverinfosrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'